#!/bin/sh
WS2300_SCRIPT=$0
if [ -h "${WS2300_SCRIPT}" ] ; then
   WS2300_SCRIPT=`readlink -f "$0"`
fi

WS2300_HOME=`dirname ${WS2300_SCRIPT}`
WS2300_CLASSPATH=$WS2300_HOME/resources

for jar in $WS2300_HOME/*.jar
do
    WS2300_CLASSPATH="${WS2300_CLASSPATH}:${jar}"
done

f_usage() {
        echo "Usage:"
        echo "$0 proxy|station|device [-jvmArgs] args "
        echo "proxy = Start up a proxy for the WS2300 device"
        echo "station = Read weather data from the WS2300 station"
        echo "device = Read/Write raw binary data from the WS2300"
        echo "If no args are supplied, usage for that command will be printed"
        echo "Don't forget jvmArg -Dgnu.io.rxtx.SerialPorts=<your non standard serial port>"
        exit 1;
}

f_trap() {
 kill $JAVA_JOB
} 

JVM_ARGS="-Dlogback.console=System.out"

while [ $# -gt 0 ]
do

case "$1" in 
        'proxy')
           MAIN_CLASS=au.com.lastweekend.ws2300.proxy.WS2300Proxy
           if [ $# -ge 3 -a "$2" = "i" ] ; then
               #Running proxy behind interceptty - use System.err
               COMMAND_ARGS="$2 $3 -Dlogback.console=System.err"
               shift 2 
           fi
           ;;
        "station")
           MAIN_CLASS=au.com.lastweekend.openjaws.WS2300Station
           ;;
        "device")
           MAIN_CLASS=au.com.lastweekend.ws2300.SerialDevice
           ;;
    -*)
       if [ "$MAIN_CLASS" ] ; then
           COMMAND_ARGS="$COMMAND_ARGS $1"
       else
           JVM_ARGS="$JVM_ARGS $1"
       fi
       ;;
    *)
       COMMAND_ARGS="$COMMAND_ARGS $1"
      ;;
esac

shift

done

[ "$MAIN_CLASS" ] || f_usage

java -cp $WS2300_CLASSPATH $JVM_ARGS $MAIN_CLASS $COMMAND_ARGS &
JAVA_JOB=$!

trap f_trap TERM
wait $JAVA_JOB